#include "BasicGeometry.h"
#include "Renderer.h"

namespace Nezha
{
	BasicGeometry::BasicGeometry(const _string& name, RenderMesh* rm)
		:SceneNode(name)
	{
		NZ_ASSERT(rm);
		mMeshSubsets.resize(1);
		mMeshSubsets[0] = rm;
		rm->_setSceneHierarchy(static_cast<SceneNode*>(this));
		mLocalAABB = rm->getBounding();
	}

	BasicGeometry::BasicGeometry(const _string& name, const PArray<RenderMesh*>& subMeshs)
		:SceneNode(name)
	{
		mMeshSubsets.resize(subMeshs.size());

		for(u32 i = 0; i < subMeshs.size(); i++)
		{
			NZ_ASSERT(subMeshs[i]);
			mMeshSubsets[i] = subMeshs[i];
			mMeshSubsets[i]->_setSceneHierarchy(static_cast<SceneNode*>(this));
			mLocalAABB.mergeAABB(mMeshSubsets[i]->getBounding());
		}
	}

	void BasicGeometry::addToRenderQueue()
	{
		// TODO

		for(MeshSubsets::iterator it = mMeshSubsets.begin(); it != mMeshSubsets.end(); it++)
		{
			if(!(*it)->getSpatial())
			{
				(*it)->_setSceneHierarchy(static_cast<SceneNode*>(this));
			}

			Renderer::GetGlobal()->requestRenderQueue(static_cast<RenderObject*>((*it).get()));
		}
	}

	SceneNode* BasicGeometry::getSpatial()
	{
		return static_cast<SceneNode*>(this);
	}

	void BasicGeometry::update(float dt)
	{
		// TODO
	}

	void BasicGeometry::setMaterial(u32 i, const MaterialPtr& mat)
	{
		for(MeshSubsets::iterator it = mMeshSubsets.begin(); it != mMeshSubsets.end(); it++)
		{
			(*it)->setMaterial(i, mat);
		}
	}

	RenderMeshPtr BasicGeometry::getSubMesh(u32 i)
	{
		NZ_ASSERT(i < mMeshSubsets.size());

		return mMeshSubsets[i];
	}

	void BasicGeometry::updateGeometryBound(AABB& aabb) const
	{
		aabb = mLocalAABB;

		//for(MeshSubsets::const_iterator it = mMeshSubsets.begin(); it != mMeshSubsets.end(); it++)
		//{
		//	aabb.mergeAABB((*it)->getBounding());
		//}
	}

}